package cmpe451.group7.dbserver.dao;

import java.util.List;

import javax.persistence.EntityManager;

import cmpe451.group7.dbserver.entity.User;
import cmpe451.group7.dbserver.service.Dba;

public class UserDAO {

	// low level DAO method in UserDao, expecting a transaction to already exist
	public static User createUser(Dba dba, String name, String username,
			String password) {

		EntityManager em = dba.getActiveEm();
		User user = new User(name, username, password);
		em.persist(user);

		return user;
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		Dba dba = new Dba(true); // open in readOnly mode

		try {
			return dba.getActiveEm().createQuery("from User u order by u.name")
					.getResultList();
		} finally {
			dba.closeEm();
		}
	}

	public User findUser(long id) {
		Dba dba = new Dba(true); // open in readOnly mode

		try {
			return dba.getById(User.class, id);
		} finally {
			dba.closeEm();
		}
	}
}
